#include "text_label.h"
#include <string>
textLabel *textLabel::createTextLabel(screen *parent,const char *text_, char *path_, int fontSize_,Anchor anchor)
{
    auto label = new textLabel();
    label->setFont(path_, fontSize_);
    label->setText(text_);
    label->setAnchor(anchor);
    label->updateSize();
    if(parent){ 
        parent->addChild(label);
        label->setParent(parent);
    }
    return label;
}

void textLabel::clean()
{
    if(!ttfText)return;
    TTF_DestroyText(ttfText);
    node_affiliate::clean();
}

void textLabel::setPath(char *path_)
{
    path = path_;
    //有可能是新的ttf_font，需要从AssetStore重新加载
    //然后设置TTF_Text里的ttf_font
    auto font = game_.getAssetStore()->getFont(path, fontSize);
    TTF_SetTextFont(ttfText,font);
    updateSize();
}

void textLabel::setFont(char *path_, int fontSize_)
{
    path = path_;
    fontSize = fontSize_;
    auto font = game_.getAssetStore()->getFont(std::string(path), fontSize);
    if(!ttfText)ttfText =game_.createText("",path,fontSize);
    TTF_SetTextFont(ttfText,font);
    updateSize();
}

void textLabel::setFontSize(int fontSize_)
{
    fontSize = fontSize_;
    //有可能是新的ttf_font，需要从AssetStore重新加载
    //然后设置TTF_Text里的ttf_font
    auto font = game_.getAssetStore()->getFont(path, fontSize);
    TTF_SetTextFont(ttfText,font);
    updateSize();
}

void textLabel::updateSize()
{
    int width, height;
    TTF_GetTextSize(ttfText, &width, &height);
    setSize(glm::vec2(width, height));
}

void textLabel::render()
{
    node_affiliate::render();
    auto pos = parent_->getRenderPosition() + offset_;
    TTF_DrawRendererText(ttfText, pos.x, pos.y);
}

void textLabel::setText(const char *text_){ 
    std::string text(text_);
    TTF_SetTextString(ttfText, text_,text.length());
    updateSize();
};
